package symbol;

/**
 * 符号表
 */
public class SymbolTable<Key, Value> {

    private Node head;
    private int N;

    public SymbolTable() {
        N = 0;
        head = new Node(null, null, null);
    }


    public void put(Key key, Value value) {
        Node n = head;
        while (n.next != null) {
            n = n.next;
            if (n.key.equals(key)) {
                n.value = value;
                return;
            }

        }

        Node oldFirst = head.next;
        head.next = new Node(key, value, oldFirst);
        N++;
    }

    public Value get(Key key) {
        Node n = head;
        while (n.next != null) {
            Node current = n.next;
            if (current.key.equals(key)) {
                return current.value;
            }
            n = n.next;
        }
        return null;
    }

    public void delete(Key key) {
        Node n = head;
        while (n.next != null) {
            if (n.next.key.equals(key)) {
                n.next = n.next.next;
                N--;
                return;
            }
            n = n.next;
        }
    }

    public int size() {
        return N;
    }

    private class Node {
        public Key key;
        public Value value;
        public Node next;

        public Node(Key key, Value value, Node next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }
    }

    public static void main(String[] args) {

        SymbolTable<Integer, String> st = new SymbolTable<>();
        st.put(1, "张三");
        st.put(3, "李四");
        st.put(5, "王五");
        System.out.println(st.size());
        st.put(1, "老三");
        System.out.println(st.get(1));
        System.out.println(st.size());
        st.delete(1);
        System.out.println(st.size());
    }
}
